package com.easyadmin.controller;


import com.easyadmin.entity.enums.ResponseCodeEnum;
import com.easyadmin.entity.enums.ResponseStatusEnum;
import com.easyadmin.entity.vo.AjaxResponseVO;
import com.easyadmin.exception.BusinessException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.NoHandlerFoundException;

import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.UndeclaredThrowableException;

@RestControllerAdvice
public class GlobalExceptionHandlerController extends ABaseController {

    private static final Logger logger = LoggerFactory.getLogger(GlobalExceptionHandlerController.class);

    /**
     *
     * @Description: 捕获全局异常, 处理所有不可知的异常
     *
     * @auther: 多多洛
     * @date: 11:44 2020/11/21
     * @param: [e, request]
     * @return: java.lang.Object
     *
     */
    @ExceptionHandler(value = Exception.class)
    Object handleException(Exception e, HttpServletRequest request) {
        AjaxResponseVO ajaxResponse = new AjaxResponseVO();
        if (e instanceof NoHandlerFoundException) {
            logger.error("请求错误，请求地址{}, 不存在", request.getRequestURL());
            ajaxResponse.setCode(ResponseCodeEnum.CODE_404.getCode());
            ajaxResponse.setInfo(ResponseCodeEnum.CODE_404.getDesc());
            ajaxResponse.setStatus(ResponseStatusEnum.ERROR.getStatus());
        } else if (e instanceof UndeclaredThrowableException) {
            Throwable bizE = ((UndeclaredThrowableException) e).getUndeclaredThrowable();
            if (bizE instanceof BusinessException) {
                BusinessException biz = (BusinessException) bizE;
                ajaxResponse.setCode(biz.getCode());
                ajaxResponse.setInfo(biz.getMessage());
                ajaxResponse.setStatus(ResponseStatusEnum.ERROR.getStatus());
            }
        } else {
            logger.error("请求参数错误，请求地址{}, msg {}", request.getRequestURL(), e);
            ajaxResponse.setCode(ResponseCodeEnum.CODE_600.getCode());
            ajaxResponse.setInfo(ResponseCodeEnum.CODE_600.getDesc());
            ajaxResponse.setStatus(ResponseStatusEnum.ERROR.getStatus());
        }
        return ajaxResponse;
    }
}